package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.enums.ValidationEnums;
import com.example.demo.mapper.ValidationMapper;
import com.example.demo.pojo.Email.Emailnumber;
import com.example.demo.pojo.Email.Validation;
import com.example.demo.pojo.R;
import com.example.demo.service.EmailnumberService;
import com.example.demo.service.ValidationService;
import com.xiaoleilu.hutool.date.DateTime;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.util.Date;

import static com.example.demo.utils.ConstantUtils.*;

@Service
@Slf4j
public class ValidationServiceImpl extends ServiceImpl<ValidationMapper, Validation> implements ValidationService {

    @Autowired
    public ValidationMapper validationMapper;
    @Autowired
    public EmailnumberService emailnumberService;

    @Resource
    public JavaMailSender javaMailSender;


    @Transactional
    public void saveCode(String email, String code, int type, DateTime offsiteMinute) {
        // 删除同类型的验证
        QueryWrapper<Validation> update = new QueryWrapper<>();
        update.eq("email", email);
        update.eq("type", type);
        validationMapper.selectOne(update);
        remove(update);
        Validation validation = new Validation();
        validation.setEmail(email);
        validation.setCode(code);
        validation.setType(type);
        validation.setTime(offsiteMinute);
        // 新增
        save(validation);
    }


    @Override
    @Transactional
    public R sendFindEmail(String email) {
        LocalDate day = LocalDate.now();
        Date date = new Date();
        //查询同类型的邮件
        QueryWrapper<Validation> Wrapper = new QueryWrapper<>();
        Wrapper.eq("email", email);
        Wrapper.eq("type", ValidationEnums.FIND_PASSWORD.getType());
        Wrapper.ge("time", date);
        Validation validation = validationMapper.selectOne(Wrapper);
        if (validation == null) {
            // 发送HTML邮件
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            try {
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
                messageHelper.setFrom(new InternetAddress(currentEmail_1));
                messageHelper.setSentDate(new Date());
                messageHelper.setSubject("找回密码验证");
                String findCode = RandomUtil.randomNumbers(CAPTCHA_LENGTH);
                String htmlContent = "<!DOCTYPE html>\n" +
                        "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                        "    <title>找回密码验证</title>\n" +
                        "    <style>\n" +
                        "        body {\n" +
                        "            font-family: Arial, sans-serif;\n" +
                        "            background-color: #f7f7f7;\n" +
                        "            margin: 0;\n" +
                        "            padding: 0;\n" +
                        "        }\n" +
                        "\n" +
                        "        .container {\n" +
                        "            max-width: 600px;\n" +
                        "            margin: 20px auto;\n" +
                        "            background-color: #ffffff;\n" +
                        "            padding: 20px;\n" +
                        "            border-radius: 5px;\n" +
                        "            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n" +
                        "        }\n" +
                        "\n" +
                        "        h1 {\n" +
                        "            color: #333333;\n" +
                        "            text-align: center;\n" +
                        "        }\n" +
                        "\n" +
                        "        p {\n" +
                        "            color: #666666;\n" +
                        "            font-size: 16px;\n" +
                        "            line-height: 1.5;\n" +
                        "        }\n" +
                        "\n" +
                        "        .code {\n" +
                        "            font-size: 24px;\n" +
                        "            font-weight: bold;\n" +
                        "            color: #0088cc;\n" +
                        "        }\n" +
                        "\n" +
                        "        .footer {\n" +
                        "            margin-top: 20px;\n" +
                        "            text-align: center;\n" +
                        "        }\n" +
                        "\n" +
                        "        .footer p {\n" +
                        "            font-size: 14px;\n" +
                        "            color: #999999;\n" +
                        "        }\n" +
                        "    </style>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "    <div class=\"container\">\n" +
                        "        <h1>找回密码验证</h1>\n" +
                        "        <p>尊敬的用户：</p>\n" +
                        "        <p>您的验证码为：<span class=\"code\">" + findCode + "</span>，有效期为2分钟。</p>\n" +
                        "        <p>如果非本人操作，请忽略此邮件！</p>\n" +
                        "        <div class=\"footer\">\n" +
                        "            <p>此邮件由系统自动发送，请勿回复。</p>\n" +
                        "        </div>\n" +
                        "    </div>\n" +
                        "</body>\n" +
                        "</html>";
                messageHelper.setText(htmlContent, true);
                messageHelper.setTo(email);
                javaMailSender.send(mimeMessage);
                log.info("发送成功");
                // 将数据存入数据库
                saveCode(email, findCode, ValidationEnums.FIND_PASSWORD.getType(), DateUtil.offsiteMinute(new Date(), CAPTCHA_EXPIRATION_TIME));
                // 统计发送次数并记录到数据库
                recordEmailCount(day, currentEmail_1);
                return R.success("验证码已发送，请注意查收！");
            } catch (MessagingException e) {
                log.error("发送邮件时出错：{}", e.getMessage());
                return R.failed("发送邮件时出错！");
            }
        }
        return R.failed("您的验证码还在有效期！无需再次获取！");
    }


    @Transactional
    void recordEmailCount(LocalDate now, String email) {
        int currentCount = emailnumberService.getEmailCountByTypeAndDate(now);

        if (currentCount >= MAX_EMAIL_COUNT) {
            // 达到每日使用上限，返回提示

            // 这里可以根据需要返回合适的提示信息
            return;
        }

        Emailnumber emailnumber = new Emailnumber();
        emailnumber.setTime(now);

        if (currentCount == 0) {
            // 今日没有记录，添加新记录
            emailnumberService.save(emailnumber);
        } else {
            // 今日已有记录，更新次数
            emailnumberService.update().setSql("number = number + 1").update();

        }
    }

}
